package com.tjec.project.projectLeaderWorkbeanch.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.tjec.common.constant.Constants;
import com.tjec.common.utils.DateUtils;
import com.tjec.common.utils.SecurityUtils;
import com.tjec.common.utils.StringUtils;
import com.tjec.framework.interceptor.annotation.RepeatSubmit;
import com.tjec.project.companyLibrary.domain.BmsExpertCompany;
import com.tjec.project.mdmSynchronous.domain.BmsProjectLeader;
import com.tjec.project.mdmSynchronous.service.IBmsProjectLeaderService;
import com.tjec.project.projectLeaderWorkbeanch.domain.BmsLeaderMember;
import com.tjec.project.projectLeaderWorkbeanch.domain.BmsMdExpertType;
import com.tjec.project.projectLeaderWorkbeanch.domain.ExpertsUseExport;
import com.tjec.project.projectLeaderWorkbeanch.service.ExpertsUseExportMapperService;
import com.tjec.project.projectLeaderWorkbeanch.service.IBmsLeaderMemberService;
import com.tjec.project.projectLeaderWorkbeanch.service.IBmsMdExpertTypeService;
import com.tjec.project.projectWorkbench.domain.BmsProjectMember;
import com.tjec.project.system.domain.BmsAttachment;
import com.tjec.project.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.tjec.framework.aspectj.lang.annotation.Log;
import com.tjec.framework.aspectj.lang.enums.BusinessType;
import com.tjec.project.projectLeaderWorkbeanch.domain.BmsExpertPerson;
import com.tjec.project.projectLeaderWorkbeanch.service.IBmsExpertPersonService;
import com.tjec.framework.web.controller.BaseController;
import com.tjec.framework.web.domain.AjaxResult;
import com.tjec.common.utils.poi.ExcelUtil;
import com.tjec.framework.web.page.TableDataInfo;

/**
 * 个人专家Controller
 * 
 * @author tjec
 * @date 2020-04-20
 */
@Api(value = "项目负责人工作台-专家清单管理接口" , tags = {"项目负责人工作台-专家清单管理接口"})
@RestController
@RequestMapping("/projectLeader/personalExpert")
public class BmsExpertPersonController extends BaseController
{
    @Autowired
    private IBmsExpertPersonService bmsExpertPersonService;

    @Autowired
    private IBmsMdExpertTypeService bmsMdExpertTypeService;

    @Autowired
    private ExpertsUseExportMapperService expertsUseExportMapperService;

    @Autowired
    private IBmsLeaderMemberService bmsLeaderMemberService;

    @Value("${sftp.http}")
    private String http;
    @Value("${sftp.ip}")
    private String ip;

    /**
     * 项目负责人下拉列表
     */
    @ApiOperation("项目负责人下拉列表")
//    @PreAuthorize("@ss.hasPermi('projectLeader:personalExpert:leaderList')")
    @GetMapping("/leaderList")
    public AjaxResult leaderList(BmsLeaderMember bmsLeaderMember)
    {
        if(bmsLeaderMember.getUserId() == null){
            bmsLeaderMember.setUserId(SecurityUtils.getLoginUser().getUser().getUserId());
        }
        bmsLeaderMember.setRole("1");
        List<BmsLeaderMember> list = bmsLeaderMemberService.selectBmsLeaderMemberList(bmsLeaderMember);
        return AjaxResult.success(list);
    }

    /**
     * 查询个人专家列表
     */
    @ApiOperation("查询个人专家列表")
//    @PreAuthorize("@ss.hasPermi('projectLeader:personalExpert:list')")
    @GetMapping("/list")
    public TableDataInfo list(BmsExpertPerson bmsExpertPerson)
    {
        startPage();
        List<BmsExpertPerson> list = bmsExpertPersonService.selectBmsExpertPersonList(bmsExpertPerson);
        for (BmsExpertPerson expertPerson : list) {
            parsExpertPerson(expertPerson);
        }
        return getDataTable(list);
    }

    /**
     *
     * @param expertPerson
     * @return
     */
    public void parsExpertPerson(BmsExpertPerson expertPerson){
        if(expertPerson == null){
            return;
        }
        if(StringUtils.isNotBlank(expertPerson.getProfessionCategory())){
            List<BmsMdExpertType> professionCategoryExpertType = bmsMdExpertTypeService.selectBmsMdExpertTypeByGuids(expertPerson.getProfessionCategory().split(";"));
            String professionCategoryNames = "";
            for (BmsMdExpertType bmsMdExpertType : professionCategoryExpertType) {
                professionCategoryNames += bmsMdExpertType.getCname()+";";
            }
            expertPerson.setProfessionCategoryName(professionCategoryNames);
        }
        if(StringUtils.isNotBlank(expertPerson.getProfessionCategory())){
            expertPerson.setProfessionCategorys( expertPerson.getProfessionCategory().split(";"));
        }
        if(StringUtils.isNotBlank(expertPerson.getBusinessMerit())){
            expertPerson.setBusinessMerits( expertPerson.getBusinessMerit().split(";"));
        }
        if(StringUtils.isNotBlank(expertPerson.getIndustryMerit())){
            expertPerson.setIndustryMerits( expertPerson.getIndustryMerit().split(";"));
        }
        if(!CollectionUtils.isEmpty(expertPerson.getBmsAttachments())){
            ArrayList<String> attIds = new ArrayList<>();
            for (BmsAttachment bmsAttachment : expertPerson.getBmsAttachments()) {
                bmsAttachment.setStoragePath(http + ip +Constants.RESOURCE_PREFIX + bmsAttachment.getStoragePath());
                attIds.add(bmsAttachment.getGuid());
            }
            expertPerson.setAttachmentIds(attIds);
        }
    }

    /**
     * 获取个人专家详细信息
     */
    @ApiOperation("获取个人专家详细信息")
    @ApiImplicitParam(name = "guid", value = "个人专家guid", required = true, dataType = "String", paramType = "path")
//    @PreAuthorize("@ss.hasPermi('projectLeader:personalExpert:query')")
    @GetMapping(value = "/{guid}")
    public AjaxResult getInfo(@PathVariable("guid") String guid)
    {
        BmsExpertPerson bmsExpertPerson = bmsExpertPersonService.selectBmsExpertPersonByGuid(guid);
        parsExpertPerson(bmsExpertPerson);
        return AjaxResult.success(bmsExpertPerson);
    }

    /**
     * 新增个人专家
     */
    @ApiOperation("新增个人专家")
    @ApiImplicitParam(name = "bmsExpertPerson", value = "新增个人专家", dataType = "BmsExpertPerson")
    @Log(title = "个人专家", businessType = BusinessType.INSERT)
//    @PreAuthorize("@ss.hasPermi('projectLeader:personalExpert:add')")
    @RepeatSubmit
    @PostMapping
    public AjaxResult add(@RequestBody BmsExpertPerson bmsExpertPerson)
    {
        //校验是否重复
        BmsExpertPerson bmsExpertPersonCheck = new BmsExpertPerson();
        bmsExpertPersonCheck.setIdentityCard(bmsExpertPerson.getIdentityCard());
        bmsExpertPersonCheck.setProjectLeader(bmsExpertPerson.getProjectLeader());
        bmsExpertPersonCheck.setName(bmsExpertPerson.getName());
        bmsExpertPersonCheck.setPhonenumber(bmsExpertPerson.getPhonenumber());
        List<BmsExpertPerson> list = bmsExpertPersonService.selectBmsExpertPersonList(bmsExpertPersonCheck);
        if(null != list && list.size() > 0){
            return AjaxResult.error("新增专家清单'" + bmsExpertPerson.getName() + "'失败，专家身份证号、姓名、手机号在专家清单管理中同时重复");
        }
        return toAjax(bmsExpertPersonService.insertBmsExpertPerson(bmsExpertPerson));
    }

    /**
     * 修改个人专家
     */
    @ApiOperation("修改个人专家")
    @ApiImplicitParam(name = "bmsExpertPerson", value = "修改个人专家", dataType = "BmsExpertPerson")
//    @PreAuthorize("@ss.hasPermi('projectleader:personalexpert:edit')")
    @Log(title = "个人专家", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BmsExpertPerson bmsExpertPerson)
    {
        //校验是否重复
        BmsExpertPerson bmsExpertPersonCheck = new BmsExpertPerson();
        bmsExpertPersonCheck.setIdentityCard(bmsExpertPerson.getIdentityCard());
        bmsExpertPersonCheck.setProjectLeader(bmsExpertPerson.getProjectLeader());
        bmsExpertPersonCheck.setName(bmsExpertPerson.getName());
        bmsExpertPersonCheck.setPhonenumber(bmsExpertPerson.getPhonenumber());
        List<BmsExpertPerson> list = bmsExpertPersonService.selectBmsExpertPersonList(bmsExpertPersonCheck);
        //过滤当前修改专家ID
        list = list.stream().filter(s -> !s.getGuid().equals(bmsExpertPerson.getGuid())).collect(Collectors.toList());
        if(null != list && list.size() > 0){
            return AjaxResult.error("修改专家清单'" + bmsExpertPerson.getName() + "'失败，专家身份证号、姓名、手机号在专家清单管理中同时重复");
        }
        return toAjax(bmsExpertPersonService.updateBmsExpertPerson(bmsExpertPerson));
    }

    /**
     * 删除个人专家
     */
//    @PreAuthorize("@ss.hasPermi('projectleader:personalexpert:remove')")
    @Log(title = "个人专家", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(bmsExpertPersonService.deleteBmsExpertPersonByIds(ids));
    }

    /**
     * 查询专家专业分类列表
     */
    @ApiOperation("查询专家专业分类列表")
//    @PreAuthorize("@ss.hasPermi('projectleader:personalexpert:expertTypeList')")
    @GetMapping("/expertTypeList")
    public TableDataInfo list(BmsMdExpertType bmsMdExpertType)
    {
        startPage();
        if(null == bmsMdExpertType.getType()||("").equals(bmsMdExpertType.getType())){
            bmsMdExpertType.setType("0");
        }
        List<BmsMdExpertType> list = bmsMdExpertTypeService.selectBmsMdExpertTypeList(bmsMdExpertType);
        return getDataTable(list);
    }

    /**
     * 查询专家使用情况
     */
    @ApiOperation("查询专家使用情况")
//    @PreAuthorize("@ss.hasPermi('projectLeader:personalExpert:expertUseList')")
    @GetMapping("/expertUseList")
    public TableDataInfo expertUseList(ExpertsUseExport expertsUseExport)
    {
        startPage();
        List<ExpertsUseExport> list = expertsUseExportMapperService.selectExpertsUseExportList(expertsUseExport);
        return getDataTable(list);
    }

    /**
     * 导出专家使用情况
     */
    @ApiOperation("导出专家使用情况")
    @Log(title = "专家使用情况", businessType = BusinessType.EXPORT)
//    @PreAuthorize("@ss.hasPermi('projectLeader:personalExpert:exportExpertsUse')")
    @GetMapping("/expertExpertUse")
    public AjaxResult export(ExpertsUseExport expertsUseExport)
    {
        List<ExpertsUseExport> list = expertsUseExportMapperService.selectExpertsUseExportList(expertsUseExport);
        for (ExpertsUseExport useExport : list) {
            if(StringUtils.isBlank(useExport.getProjectStatus())){
                useExport.setProjectStatus("");
            }else {
                if (useExport.getProjectStatus().equals("0")) {
                    useExport.setProjectStatus("筹备");
                } else if (useExport.getProjectStatus().equals("1")) {
                    useExport.setProjectStatus("进行中");
                } else if (useExport.getProjectStatus().equals("2")) {
                    useExport.setProjectStatus("成果交付");
                } else if (useExport.getProjectStatus().equals("3")) {
                    useExport.setProjectStatus("项目完成");
                } else if (useExport.getProjectStatus().equals("4")) {
                    useExport.setProjectStatus("项目暂停");
                } else if (useExport.getProjectStatus().equals("5")) {
                    useExport.setProjectStatus("项目终止");
                } else if (useExport.getProjectStatus().equals("6")) {
                    useExport.setProjectStatus("项目作废");
                }
            }
        }
        ExcelUtil<ExpertsUseExport> util = new ExcelUtil<ExpertsUseExport>(ExpertsUseExport.class);
        return util.exportExcelMergeSameColumn(list, "ExpertsUse", getMergedRegionIndexs(list, 3));
    }

    /**
     * 根据数据获取需要合并的单元格的集合
     * @param list
     * @param mergeCols
     * @return
     */
    private List<String> getMergedRegionIndexs(List<ExpertsUseExport> list, int mergeCols){
        List<String> mergedRegionIndexs  = new ArrayList<>();
        if(!CollectionUtils.isEmpty(list)){
            int startRow = 0;
            for (int i = 0; i < list.size(); i++) {
                if(i==0){
                    continue;
                }
                if((list.get(i).getProjectId()).equals(list.get(i-1).getProjectId())){
                    startRow++;
                }else{
                    if(startRow>0){
                        for (int j = 0; j < mergeCols; j++) {
                            mergedRegionIndexs.add(i-startRow+";"+i+";"+j+";"+j+";");
                        }
                        startRow =0;
                    }
                }
            }
            if(startRow>0){
                for (int j = 0; j < mergeCols; j++) {
                    mergedRegionIndexs.add(list.size()-startRow+";"+list.size()+";"+j+";"+j+";");
                }
            }
        }
        return mergedRegionIndexs;
    }
}
